package com.lin;

/**
 * @Author zimingl
 * @Date 2023/5/1 20:12
 * @Description: ThreadLocalDemo
 */
public class ThreadLocalDemo {
    // 创建一个 ThreadLocal 对象
    private static ThreadLocal<String> localVar = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程并启动
        Thread thread1 = new Thread(() -> {
            localVar.set("Thread 1");
            printLocalVar(); // 输出当前线程的变量副本
        });
        Thread thread2 = new Thread(() -> {
            localVar.set("Thread 2");
            printLocalVar(); // 输出当前线程的变量副本
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }

    // 输出当前线程的变量副本
    private static void printLocalVar() {
        System.out.println(Thread.currentThread().getName() + ": " + localVar.get());
    }
}
